/*认购、抢购*/
define(['jquery', 'api', 'util', 'user', 'Vue', 'text!pages/index/productdetail.html', 'pages/index/goodsModel'], function($, api, util, user, Vue, tpl, goodsModel) {
    var vm,
        timer,
        flashsaleTimer,
        endtimelimitChange, //保存不断减少的抢购结束时间
        goodscode,
        slGoodsCountTimer, // 商品统计信息计时器句柄
        code2flashsale,
        controller = {
            init: function(code) {
                goodscode = code;
                this.clearFullTimer();

                api.footerShow(0);
                api.setTitle(L('html_title_index_productdetail'));
                api.headerShow(1);
				api.headerTitle(L('html_title_index_productdetail'));
				api.headerRightTitle('');
				api.headerRightLink('#/');
                
                if (vm) {
                    vm.show = true;
                    vm.desc = '';
                    vm.subscription = '';
                } else {
                    this.render();
                }

                // 当前抢购数据
                this.loadGoods(goodscode);

            },
            render: function() {
                var that = this;
                $('#pages').append('<div id="productdetail"></div>');
                vm = new Vue({
                    el: '#productdetail',
                    data: {
                        show: true,
                        userFund: {}, //用户资金
                        isFlashsale: false, //抢购已开始
                        hasNextFlashsale: false, //是否有下一场抢购
                        flashsale:{},//进行中的抢购数据
                        flashsalenext:{
                        	starttime:null,
                        	endtime:null
                        },//下一场抢购数据
                        isEnd: false, //结束购买
                        holdamount: 0, //用户持仓数
                        starttime: '',
                        endtime: '',
                        goods: {},
                        formCount:1,// 要购买数量
                        formCanamount:0,// 可认购数量
                        desc: '',
                        subscription: '',
                        formshow: false,
                        showDesc: true,
                        flashsaleTime: '00:00:00'//抢购剩余时间
                    },
                    watch:{
                    	formCount:function(v,old){
                    		if(isNaN(v) || v==''){
                    			this.formCount='';
                    		}else{
                    			this.formCount = parseInt(v);
                    		}
                    	}
                    },
                    computed: {
                        btnName: function() {//按钮内容
                            if (this.isFlashsale) {
                                return '立即抢购';
                            } else {
                                if (this.goods.issuestatus == 55) {
                                    vm.isEnd = true;
                                    return '认购结束';
                                }
                                return '我要认购';
                            }
                        },
                        priceCount: function() {//认购金额计算
                            // 认购价格*可认购数量
                            if(this.isFlashsale){
                            	var total = parseFloat(this.goods.flashsale.iprice) * this.formCount;
                            	return this.goods.flashsale ? util.priceFormat(this.goods.mindecimal, total) : 0;
                            }else{
                            	var total = parseFloat(this.goods.issueprice) * this.formCount;
	                            return this.goods ? util.priceFormat(this.goods.mindecimal, total) : 0;
                            }
                        }
                    },
                    filters: {
                        priceFormatMindecimal: function(v, mindecimal) {
                            return v ? util.priceFormat(mindecimal, v) : '';
                        },
                        date: function(time) {
                            return time ? new Date(time * 1000).format('yyyy-MM-dd hh:mm:ss') : '';
                        }
                    },
                    methods: {
                        switchShowDesc: function(i) {
                            this.showDesc = i
                        },
                        setCanamount: function() {
                            that.loadSlGoodsCount();
                        },
                        showForm: function() {
                            if (this.isEnd)
                                return;//是认购结束
                            if (!user.checkLogin())
                                return;//没登录，自动跳转登录
                            this.formshow = 1;//显示表单
                            this.setCanamount();//设置可买数量
                        },
                        hideForm: function() {
                            this.formshow = 0;
                        },
                        resetForm: function() {
                            this.formCount = 1;
                            this.formCanamount = this.formCanamount>0 ? this.formCanamount:0;
                            this.isEnd = false;
                            this.isFlashsale = false;
                            this.hasNextFlashsale = false;
                            this.hideForm();
                        },
                        subForm: function() {//立即认购
                            if (that.isValid({formCount:this.formCount})) {
                                if (this.isFlashsale) {
                                    //执行抢购
                                    this.flashsaleSub(this.goods.flashsale.saleid, goodscode, vm.formCount);
                                    return;
                                }
                                api.createSlOrder(
                                    {goodscode: goodscode, amount: vm.formCount},
	                                function(rs) {
	                                    if (rs.retcode == 0) {
	                                        util.msg('认购成功！');
	                                        vm.resetForm();
	                                        setTimeout(that.loadGoods(goodscode), 1000);
	                                    } else if (rs.retcode !== '0') {
	                                        util.dealErrorCode(rs.retcode);
	                                    }
	                                }
                                );
                            }
                        },
                        flashsaleSub: function(saleid, code, num) {//抢购提交
                        	// 检查数量限制
                        	if(num < this.goods.flashsale.minpurchase){
                        		util.msg('最小购买数量不能小于'+this.goods.flashsale.minpurchase);
                        		return;
                        	}
                        	if(num > this.goods.flashsale.maxpurchase){
                        		util.msg('最大购买数量不能大于'+this.goods.flashsale.maxpurchase);
                        		return;
                        	}
                        	// isrepurchaseable 可重复抢购:'1' - 允许;'2' - 不允许
                        	// purchaseamount 已抢购数量
                        	
                            api.flashsale({saleid: saleid, goodscode: code, purchasenum: num}, function(rs) {
                                if (rs.retcode === '0') {
                                    util.msg('抢购成功！');
                                    vm.resetForm();
                                    setTimeout(that.loadGoods(goodscode), 1000);
                                } else {
                                	util.dealErrorCode(rs.retcode);
                                }
                            });
                        },
                    },
                    template: tpl
                });//End VUE

            },
            initUserInfo: function() {
                api.userInfo(function(rs) {
                    if (rs.retcode == '0') {
                        vm.userFund = rs.data;
                    } else {
                        util.msg('用户信息获取失败！');
                    }
                });
            },
            isValid: function(data) {//表单验证
                var error = false,
                        errorHash = {
                            formCount: '请填写数量！'
                        };
                for (var key in errorHash) {
                    if (data[key] == '') {
                        error = errorHash[key];
                        break;
                    }
                }
                
                if (key == 'formCount' && (isNaN(data[key]) || data[key] <= 0)) {
                    error = '数量必须大于0';
                }
                if (isNaN(vm.formCanamount) || vm.formCanamount <=0 || vm.formCount > vm.formCanamount) {
                    error = '可购数量不足';
                }
                
                if (error) {
                    util.msg(error);
                    return false;
                } else {
                    return true;
                }
            },
            loadGoods: function(code) {
                var that = this,
                    cb = function() {
                        that.loadDesc(code);

                        if (user.isLogin()) {
                            that.initUserInfo();

                            api.queryGoodHold({}, function(rs) { // 持仓汇总
                                if (rs.retcode === '0' && rs.data) {
                                    rs.data.map(function(item) {
                                        if (item.goodscode == code)
                                            vm.holdamount = item.holdamount;
                                    });
                                }
                            });
                        }
                    };

                api.goodsInfo({
                    data: {goodscode: code},
                    success: function(rs) {
                        if (rs.retcode === '0') {
                            var items = [];
                            if (rs.data && rs.data.length) {
                                goodsModel.addGoods(rs.data);
                                var goods = goodsModel.codeToGoods[code];
                                vm.goods = goods ? goods : {};
                                
								if(goods.issuestatus==50){
									//有抢购活动
									if(typeof goods.flashsale != 'undefined'){
										// 0-没开始 1-正在抢购
										if(goods.flashsale.status==='0'){
											vm.hasNextFlashsale = true;
											vm.flashsalenext = goods.flashsale;
										}
										else if(goods.flashsale.status==='1'){
		                                    vm.isFlashsale = true;
		                                    vm.flashsale = goods.flashsale;
		                                    that.clearFullTimer();
		                                    //抢购倒计时
	                        				that.buyTimer()
										}
									}
									if(typeof goods.flashsalenext != 'undefined'){
										vm.hasNextFlashsale = true;
										vm.flashsalenext = goods.flashsalenext;
									}
								}
                            }
                            cb();
                        } else if (rs.retcode !== '0') {
                            util.dealErrorCode(rs.retcode);
                            cb();
                        }
                    }
                });

            },
            loadDesc: function(goodscode) {
            	api.goodsDesc(
	        		goodscode,
	        		function(rs){//suc
	            		if (rs.retcode == 0) {
	                        vm.desc = rs.data.goodsdesc; //商品介绍
	                        vm.subscription = rs.data.goodssubscription;//认购说明
	                    }
	            	},
	            	function(){//err
	            	}
	        	);
            },
            buyTimer: function() {//抢购计时
                var that = this,
                    goods = vm.goods,
                    flashsale = vm.flashsale,
                	endtimelimit = flashsale.endtime * 1000, //结束时间，时间戳毫秒
                    nowtimelimit = new Date().getTime(), //当前时间戳毫秒
                    timego=function(EndTime){
                    	var zero= function(n) {
                            var n = parseInt(n, 10);
                            if (n > 0) {
                                if (n <= 9) {
                                    n = "0" + n;
                                }
                                return String(n);
                            } else {
                                return "00";
                            }
                        }
//                  	var EndTime= new Date('2014/09/20 00:00:00');
					    var NowTime = new Date();
					    var t =EndTime - NowTime.getTime();
					    var d=0;
					    var h=0;
					    var m=0;
					    var s=0;
					    if(t>=0){
					      d=Math.floor(t/1000/60/60/24);
					      h=Math.floor(t/1000/60/60%24);
					      m=Math.floor(t/1000/60%60);
					      s=Math.floor(t/1000%60);
					    }
					    
					    if(d===0 && h===0 && m===0 && s===0){
							//抢购结束
							that.loadGoods();
							return;
						}
					    
//					    console.log(zero(d),zero(h),zero(m),zero(s));
					    endtimelimitChange -= 1000;
                        vm.flashsaleTime = [zero(h),zero(m),zero(s)].join(':');
                        that.buyTimer();
                    },
                    pms = {
                        sec: "00",
                        mini: "00",
                        hour: "00",
                        day: "00",
                        month: "00",
                        year: "0"
                    },
                    cb = function() {
                        if (!endtimelimitChange)
                            endtimelimitChange = endtimelimit;
//                      var t = new Date(endtimelimitChange).format('hh:mm:ss');

						timego(endtimelimit);
						return;

           			};//end cb
           			
				// 计时开始！
				if(flashsaleTimer)clearTimeout(flashsaleTimer);
                flashsaleTimer = setTimeout(cb, 1000);
            },
            loadSlGoodsCount: function() {//我要认购是的参数 canpurchaseamount 可认购数量
                var that = this,
                    cb = function() {
                        that.loadSlGoodsCount();
                    };
                api.slgoodsCount({goodscode: goodscode}, function(rs) {
                    if (rs.retcode === '0' && rs.data) {
                        vm.formCanamount = rs.data.canpurchaseamount;
                    } else {
                    	if(slGoodsCountTimer)clearTimeout(slGoodsCountTimer);
                        slGoodsCountTimer = setTimeout(cb, 1000);
                    }
                });
            },
            clearFullTimer:function(){
            	if (flashsaleTimer)
                    clearTimeout(flashsaleTimer);
                if (slGoodsCountTimer)
                    clearTimeout(slGoodsCountTimer);
            },
            onRouteChange: function() {
                if (vm) {
                    vm.resetForm();
                    vm.show = false;
                }
                this.clearFullTimer();
            }
        }
    return controller;
});